package com.saw96x.MyBlog.dao;

import com.saw96x.MyBlog.pojo.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Saw96x
 * @date 20/11/11 - 16:34
 *
 * 博客增删改查的dao层
 */
public interface BlogRepository extends JpaRepository<Blog, Long>, JpaSpecificationExecutor<Blog> {
    /**
     *
     * @param pageable 分页查询工具接口
     * @return 返回推荐博客的列表
     */
    @Query("select b from Blog b where b.recommend = true")
    List<Blog> findTop(Pageable pageable);

    /**
     *
     * @param query 搜索的关键字
     * @param pageable 分页查询工具接口
     * @return 返回搜索得到的博客分页列表
     */
    @Query("select b from Blog b where b.title like ?1 or b.content like ?1")
    Page<Blog> findByQuery(String query, Pageable pageable);

    /**
     *
     * @param id 更新浏览次数的博客id
     * @return 返回更新后的浏览次数
     */
    @Transactional
    @Modifying
    @Query("update Blog b set b.views = b.views+1 where b.id = ?1")
    int updateViews(Long id);

    /**
     *
     * @return 返回按博客的年份
     */
    @Query("select function('date_format',b.updateTime,'%Y') as year from Blog b group by function('date_format',b.updateTime,'%Y') order by year desc ")
    List<String> findGroupYear();

    /**
     *
     * @param year 博客归档的年份
     * @return 返回按年归档的博客列表
     */
    @Query("select b from Blog b where function('date_format',b.updateTime,'%Y') = ?1")
    List<Blog> findByYear(String year);

}






















